import * as ns from "@native";
type NS = typeof ns;
let _any = null as any;

export function call_native<K extends keyof NS, F extends NS[K]>(func: K, ...args: Parameters<F>): ReturnType<F> {
  const _any = call_native.obj();
  if (!_any)
    return Promise.reject(new Error('[call_native] App not exist')) as any;

  const fn = _any[func];
  if (typeof fn !== 'function')
    return Promise.reject(new Error(`[call_native] ${func} not exist`)) as any;

  return fn.call(_any, ...args).then((r: any) => {
    if (r.error && typeof r.error === 'string')
      throw new Error('' + r.error);
    return r;
  });
}
call_native.obj = () => {
  if (_any === false) return false;
  return (_any = (window as any)?.go?.main?.App || false)
}